using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	internal class DefaultFormat : AFormatManager
	{
		private Text _gameName;

		private VideoManager _videoManager;

		[SerializeField]
		private GameObject _adLabel;

		[SerializeField]
		public RectTransform myCanvasTransformer;

		private static RectTransform _transformer;

		private void Awake()
		{
			AFormatManager.Instance = this;
			base.gameObject.name = "CrossPromoGameObject";
			CrossPromoDisplayEvents.ShowEvent += Display;
			CrossPromoDisplayEvents.HideEvent += Hide;
			_transformer = myCanvasTransformer;
		}

		private void OnDestroy()
		{
			CrossPromoDisplayEvents.ShowEvent -= Display;
			CrossPromoDisplayEvents.HideEvent -= Hide;
		}

		private void Start()
		{
			try
			{
				_videoManager = new VideoManager(GetComponentInChildren<VideoPlayer>(), GetComponentInChildren<RawImage>());
				_gameName = GetComponentInChildren<Text>();
				_videoManager.VideoPlayer.prepareCompleted += delegate
				{
					if (Asset == null)
					{
						Hide();
					}
					else
					{
						Enable(show: true);
						CrossPromoEvents.TriggerShownEvent(Asset);
					}
				};
				Enable(show: false);
			}
			catch (Exception)
			{
			}
		}

		public override void Display()
		{
			if (IsWaiting)
			{
				IsActive = true;
			}
			if (!IsActive && !IsWaiting)
			{
				StartCoroutine(StartDisplay());
			}
		}

		private IEnumerator StartDisplay()
		{
			IsActive = true;
			IsWaiting = true;
			yield return new WaitForEndOfFrame();
			yield return WaitCrossPromoReady();
			IsWaiting = false;
			if (!IsActive || Asset == null)
			{
				yield break;
			}
			if (Asset.game.name != null)
			{
				_gameName.text = Asset.game.name;
			}
			try
			{
				_videoManager.PrepareVideo(Asset);
			}
			catch (Exception message)
			{
				CrossPromoEvents.TriggerErrorEvent(message);
			}
		}

		public static Vector3 RectTransformToScreenSpace()
		{
			Vector3[] array = new Vector3[4];
			_transformer.GetWorldCorners(array);
			Vector3 result = array[0];
			result.y = (float)Screen.height - result.y;
			return result;
		}

		public override void Hide()
		{
			IsActive = false;
			Asset = null;
			if (_videoManager != null)
			{
				_videoManager.StopVideo();
				Enable(show: false);
			}
		}

		private void Enable(bool show)
		{
			GetComponent<Image>().enabled = show;
			base.transform.GetChild(0).gameObject.SetActive(show);
			base.transform.GetChild(1).GetComponentInChildren<Image>().enabled = show;
			_adLabel.SetActive(value: false);
		}
	}
}
